<?php

namespace app\admin\model;

use app\admin\common\Constants;
use think\Cache;

class Config extends Common
{
    protected static function init()
    {
        Config::event('after_insert', function ($data) {
            if (is_array($data)) {
                foreach ($data as $item) {
                    if ($item->name == Constants::$SEAL_STATUS_KEY || $item->name == Constants::$SEAL_TYPE_KEY) {
                        $this->updateCache($item);
                    }
                }
            } else {
                if ($data->name == Constants::$SEAL_STATUS_KEY || $data->name == Constants::$SEAL_TYPE_KEY) {
                    $this->updateCache($data);
                }
            }
        });
        Config::event('after_update', function ($data) {
            if (is_array($data)) {
                foreach ($data as $item) {
                    if ($item->name == Constants::$SEAL_STATUS_KEY || $item->name == Constants::$SEAL_TYPE_KEY) {
                        $this->updateCache($item);
                    }
                }
            } else {
                if ($data->name == Constants::$SEAL_STATUS_KEY || $data->name == Constants::$SEAL_TYPE_KEY) {
                    $this->updateCache($data);
                }
            }
        });
        Config::event('after_delete', function ($data) {
            if (is_array($data)) {
                foreach ($data as $item) {
                    Cache::clear($item->name);
                }
            }
        });
    }

    private function updateCache($data)
    {
        Cache::set($data->name, $this->__textDefaultFormat($data->name));
    }

    /**
     * 通过name获取配置缓存
     * <p>例如：获取印章类型缓存配置，getConfigCacheByName({@link Constants::$SEAL_STATUS_KEY}) 返回的则是 ['1'=>['id'=>1,'name'=>'公章']]</p>
     * @param $name
     * @return array|array[]|mixed|void|null
     */
    public function getConfigCacheByName($name)
    {
        return Cache::remember($name, function () use ($name) {
            $config = $this->__textDefaultFormat($name);
            if($config==null){
                return [];
            }
            $result = [];
            foreach ($config as $key => $value) {
                $result[$value['id']] = $value;
            }
            return $result;
        });
    }

    /**
     * 通过name获取配置缓存
     * <p>例如：获取印章类型缓存配置，getConfigCacheByName({@link Constants::$SEAL_STATUS_KEY}) 返回的则是 ['1'=>['id'=>1,'name'=>'公章']]</p>
     * @param $name String 缓存KEY
     * @param $id integer 对象ID
     * @return array|array[]|mixed|void|null
     */
    public function getConfigCacheByNameEqualsAndIdEquals($name, $id)
    {
        $configCacheByName = $this->getConfigCacheByName($name);
        if ($id == null) {
            return $configCacheByName;
        }
        if (!$configCacheByName) {
            return null;
        }
        return $configCacheByName[$id];
    }

    /**
     * 获取印章类型
     *
     * <p>例如：Config::getSealTypes(1) ，返回：['id'=>1,'name'=>'合同专用章']</p>
     * <p>例如：Config::getSealTypes() ，返回：[['id'=>1,'name'=>'合同专用章'],['id'=>2,'name'=>'公章']...]</p>
     *
     * @param null $id 为空时则返回所有，找不到id为返回null
     * @return array|array[]|mixed|null
     */
    public function getSealTypes($id = null)
    {
        return $this->getConfigCacheByNameEqualsAndIdEquals(Constants::$SEAL_TYPE_KEY, $id);

    }

    /**
     * 获取印章申请状态
     *
     * <p>例如：Config::getSealTypes(1) ，返回：['id'=>1,'name'=>'合同专用章']</p>
     * <p>例如：Config::getSealTypes() ，返回：[['id'=>1,'name'=>'合同专用章'],['id'=>2,'name'=>'公章']...]</p>
     *
     * @param null $id 为空时则返回所有，找不到id为返回null
     * @return array|array[]|mixed|null
     */
    public function getSealAppFormStatues($id = null)
    {
        return $this->getConfigCacheByNameEqualsAndIdEquals(Constants::$SEAL_APPY_FORM_STATUS_KEY, $id);
    }

    /****
     * 获取印章状态
     *
     * <p>例如：Config::getSealTypes(1) ，返回：['id'=>1,'name'=>'禁用']</p>
     * <p>例如：Config::getSealTypes() ，返回：[['id'=>1,'name'=>'禁用'],['id'=>2,'name'=>'可用']...]</p>
     *
     * @param null $id 为空时则返回所有，找不到id为返回null
     */
    public function getSealStatus($id = null)
    {
        return $this->getConfigCacheByNameEqualsAndIdEquals(Constants::$SEAL_STATUS_KEY, $id);
    }
    public function getMobile($id = null)
    {
        return $this->getConfigCacheByNameEqualsAndIdEquals(Constants::$Mobile, $id);
    }
    /**
     * 换行文本数据格式化
     * @param $cacheName
     * @param $id
     * @return array|array[]|void|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function __textDefaultFormat($cacheName, $id = null)
    {
        $row = $this->where('name', 'eq', $cacheName)->find();
        if (!$row) {
            return null;
        }
        $arr = $this->__textFormatValue($row->value);
        if ($arr == null) {
            return null;
        }
        if ($id != null) {
            foreach ($arr as $key => $value) {
                if ($value['id'] == $id) {
                    return $value;
                }
            }
        } else {
            return $arr;
        }
    }

    /**
     * 换行文本格式化
     * @param $value
     * @return array|array[]|null
     */
    protected function __textFormatValue($value)
    {
        if (!$value) {
            return null;
        }
        $explode = explode(PHP_EOL, $value);
        return array_map(function ($item) {
            $item = explode('|', $item);
            return [
                'id'   => $item[0],
                'name' => $item[1],
            ];
        }, $explode);
    }


}
